<?
$SITE_ONLINE = true;

$maxusers = 1000;
$max_torrent_size = 1000000;
$announce_interval = 60 * 30;
$signup_timeout = 86400 * 3;
$max_dead_torrent_time = 24 * 3600;
$autoclean_interval = 900;
$minvotes = 1;
//$funds = "$1,000.00";

/*
if ($_SERVER["HTTP_HOST"] == "")
	$_SERVER["HTTP_HOST"] = $_SERVER["SERVER_NAME"];
if ($_SERVER["HTTP_HOST"] == "www.reztorrent.org" || $_SERVER["HTTP_HOST"] == "reztorrent.org")
	$SITEURL = "http://" . $_SERVER["HTTP_HOST"];
else
*/
	$SITEURL = "http://www.reztorrent.org";

$SITEEMAIL = "admin@reztorrent.org";

$SITENAME = "RezTorrent";

$torrent_dir = "/home/reztor/www/torrents";    # FOR UNIX
//$torrent_dir = "C:/web/Apache2/htdocs/tbsource/torrents";    # FOR WINDOWS

$announce_urls = array();
$announce_urls[] = $SITEURL . "/tracker/announce.php";
//add more announce urls here

$starttime = explode(" ", microtime()); //Split Seconds and Microseconds
$starttime = $starttime[1] + $starttime[0];  //Create a single value for start time

$smilies = array(":-)" => "smile1.gif",":smile:" => "smile2.gif",":-D" => "grin.gif",":lol:" => "laugh.gif",":w00t:" => "w00t.gif",":w000t:" => "w000t.gif",":-P" => "tongue.gif",";-)" => "wink.gif",":smirk:" => "smirk.gif",":happy:" => "mml.gif",":-|" => "noexpression.gif",":-/" => "confused.gif",":-(" => "sad.gif",":'-(" => "cry.gif",":weep:" => "weep.gif",":-O" => "ohmy.gif",":o)" => "clown.gif","8-)" => "cool1.gif","|-)" => "sleeping.gif",":laughing:" => "laughing.gif",":innocent:" => "innocent.gif",":whistle:" => "whistle.gif",":unsure:" => "unsure.gif",":closedeyes:" => "closedeyes.gif",":cool:" => "cool2.gif",":fun:" => "fun.gif",":thumbsup:" => "thumbsup.gif",":thumbsdown:" => "thumbsdown.gif",":blush:" => "blush.gif",":yes:" => "yes.gif",":no:" => "no.gif",":love:" => "love.gif",":?:" => "question.gif",":!:" => "excl.gif",":idea:" => "idea.gif",":arrow:" => "arrow.gif",":arrow2:" => "arrow2.gif",":hmm:" => "hmm.gif",":hmmm:" => "hmmm.gif",":huh:" => "huh.gif",":geek:" => "geek.gif",":look:" => "look.gif",":rolleyes:" => "rolleyes.gif",":kiss:" => "kiss.gif",":shifty:" => "shifty.gif",":blink:" => "blink.gif",":smartass:" => "smartass.gif",":sick:" => "sick.gif",":crazy:" => "crazy.gif",":wacko:" => "wacko.gif",":alien:" => "alien.gif",":wizard:" => "wizard.gif",":wave:" => "wave.gif",":wavecry:" => "wavecry.gif",":cry2:" => "cry2.gif",":baby:" => "baby.gif",":angry:" => "angry.gif",":ras:" => "ras.gif",":sly:" => "sly.gif",":devil:" => "devil.gif",":evil:" => "evil.gif",":evilmad:" => "evilmad.gif",":sneaky:" => "sneaky.gif",":axe:" => "axe.gif",":slap:" => "slap.gif",":wall:" => "wall.gif",":rant:" => "rant.gif",":jump:" => "jump.gif",":yucky:" => "yucky.gif",":horror:" => "horror.gif",":banned:" => "banned.gif",":fist:" => "fist.gif",":nugget:" => "nugget.gif",":smart:" => "smart.gif",":shutup:" => "shutup.gif",":shutup2:" => "shutup2.gif",":crockett:" => "crockett.gif",":zorro:" => "zorro.gif",":snap:" => "snap.gif",":beer:" => "beer.gif",":beer2:" => "beer2.gif",":drunk:" => "drunk.gif",":strongbench:" => "strongbench.gif",":weakbench:" => "weakbench.gif",":dumbells:" => "dumbells.gif",":music:" => "music.gif",":stupid:" => "stupid.gif",":dots:" => "dots.gif",":offtopic:" => "offtopic.gif",":spam:" => "spam.gif",":oops:" => "oops.gif",":lttd:" => "lttd.gif",":please:" => "please.gif",":sorry:" => "sorry.gif",":hi:" => "hi.gif",":yay:" => "yay.gif",":cake:" => "cake.gif",":hbd:" => "hbd.gif",":band:" => "band.gif",":punk:" => "punk.gif",":rofl:" => "rofl.gif",":bounce:" => "bounce.gif",":mbounce:" => "mbounce.gif",":thankyou:" => "thankyou.gif",":gathering:" => "gathering.gif",":hang:" => "hang.gif",":chop:" => "chop.gif",":rip:" => "rip.gif",":whip:" => "whip.gif",":judge:" => "judge.gif",":chair:" => "chair.gif",":tease:" => "tease.gif",":box:" => "box.gif",":boxing:" => "boxing.gif",":guns:" => "guns.gif",":shoot:" => "shoot.gif",":shoot2:" => "shoot2.gif",":flowers:" => "flowers.gif",":wub:" => "wub.gif",":lovers:" => "lovers.gif",":kissing:" => "kissing.gif",":kissing2:" => "kissing2.gif",":console:" => "console.gif",":group:" => "group.gif",":hump:" => "hump.gif",":hooray:" => "hooray.gif",":happy2:" => "happy2.gif",":clap:" => "clap.gif",":clap2:" => "clap2.gif",":weirdo:" => "weirdo.gif",":yawn:" => "yawn.gif",":bow:" => "bow.gif",":dawgie:" => "dawgie.gif",":cylon:" => "cylon.gif",":book:" => "book.gif",":fish:" => "fish.gif",":mama:" => "mama.gif",":pepsi:" => "pepsi.gif",":medieval:" => "medieval.gif",":rambo:" => "rambo.gif",":ninja:" => "ninja.gif",":hannibal:" => "hannibal.gif",":party:" => "party.gif",":snorkle:" => "snorkle.gif",":evo:" => "evo.gif",":king:" => "king.gif",":chef:" => "chef.gif",":mario:" => "mario.gif",":pope:" => "pope.gif",":fez:" => "fez.gif",":cap:" => "cap.gif",":cowboy:" => "cowboy.gif",":pirate:" => "pirate.gif",":pirate2:" => "pirate2.gif",":rock:" => "rock.gif",":cigar:" => "cigar.gif",":icecream:" => "icecream.gif",":oldtimer:" => "oldtimer.gif",":trampoline:" => "trampoline.gif",":banana:" => "bananadance.gif",":smurf:" => "smurf.gif",":yikes:" => "yikes.gif",":osama:" => "osama.gif",":saddam:" => "saddam.gif",":santa:" => "santa.gif",":indian:" => "indian.gif",":pimp:" => "pimp.gif",":nuke:" => "nuke.gif",":jacko:" => "jacko.gif",":ike:" => "ike.gif",":greedy:" => "greedy.gif",":super:" => "super.gif",":wolverine:" => "wolverine.gif",":spidey:" => "spidey.gif",":spider:" => "spider.gif",":bandana:" => "bandana.gif",":construction:" => "construction.gif",":sheep:" => "sheep.gif",":police:" => "police.gif",":detective:" => "detective.gif",":bike:" => "bike.gif",":fishing:" => "fishing.gif",":clover:" => "clover.gif",":horse:" => "horse.gif",":shit:" => "shit.gif",":deadhorse:" => "deadhorse.gif",":spank:" => "spank.gif",":soldiers:" => "soldiers.gif",":strike:" => "strike.gif",":morepics:" => "morepics.gif",":Boozer:" => "alcoholic.gif",":yoji:" => "yoji.gif");

$privatesmilies = array(":locked:" => "locked.gif",":rtf:" => "rtf.gif",":)" => "smile1.gif",":wink:" => "wink.gif",":D" => "grin.gif",":P" => "tongue.gif",":(" => "sad.gif",":'(" => "cry.gif",":|" => "noexpression.gif",":grrr:" => "angry.gif","O:-" => "innocent.gif",":sleeping:" => "sleeping.gif","-_-" => "unsure.gif",":clown:" => "clown.gif",":mml:" => "mml.gif");

/*

$categories = array("TV/XviD" => "cat_tv_xvid.gif","TV/x264" => "cat_tv_x264.gif","Movies/XviD" => "cat_movies_xvid.gif","Movies/x264" => "cat_movies_x264.gif","Movies/DVDR" => "cat_movies_dvdr.gif","Music" => "cat_music.gif","Books" => "cat_books.gif","Appz" => "cat_appz.gif","Games" => "cat_games.gif","XXX" => "cat_xxx.gif","Misc" => "cat_misc.gif");

$residences = array("None","Totem Park","Place Vanier","Ritsumeikan","Gage","Fairview","Thunderbird","Marine Drive","Other");

$forums = array();

$stylesheets = array("Default","Large Text");

*/

require "secrets.php";

/*
If the following defined classes are changed, remember to modify:
1. existing classes in the users table of the database
2. the get_user_class_name() function to match any changes
3. the minclassread/write/create in the forums table of the database
4. promotions and demotions in the cleanup() function
*/

define ('TBVERSION','TBDEV :: eLucid mod');
define ('UC_USER', 0);
define ('UC_POWER_USER', 1);
define ('UC_ELITE_USER', 2);
define ('UC_VIP', 3);
define ('UC_UPLOADER', 4);
define ('UC_MODERATOR', 5);
define ('UC_ADMINISTRATOR', 6);
define ('UC_SYSOP', 7);

if (!preg_match('/^www./', $_SERVER['HTTP_HOST'])) 
{
	header('HTTP/1.1 301 Moved Permanently');
	header('Location: ' . $SITEURL . $_SERVER['REQUEST_URI']);
	exit();
}

if (!$SITE_ONLINE)
	die("$SITENAME is currently down for maintenance. Please check back again later. Thanks.");

//Performs a MySQL query and records the total query count
function query($query)
{
	$result = mysql_query($query);
	$_SESSION["totalqueries"]++;
	return $result;
}

//Validates an IP address
function validip($ip)
{
	if (!empty($ip) && $ip == long2ip(ip2long($ip)))
	{
		// reserved IANA IPv4 addresses
		// http://www.iana.org/assignments/ipv4-address-space
		$reserved_ips = array (
				array('0.0.0.0','2.255.255.255'),
				array('10.0.0.0','10.255.255.255'),
				array('127.0.0.0','127.255.255.255'),
				array('169.254.0.0','169.254.255.255'),
				array('172.16.0.0','172.31.255.255'),
				array('192.0.2.0','192.0.2.255'),
				array('192.168.0.0','192.168.255.255'),
				array('255.255.255.0','255.255.255.255')
		);

		foreach ($reserved_ips as $r)
		{
				$min = ip2long($r[0]);
				$max = ip2long($r[1]);
				if ((ip2long($ip) >= $min) && (ip2long($ip) <= $max)) return false;
		}
		return true;
	}
	else return false;
}

//Validates an ID number
function is_valid_id($id)
{
	return is_numeric($id) && ($id > 0) && (floor($id) == $id);
}

//Validates an email address
function validemail($email) 
{
	return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}

//Returns an IP address
function getip() 
{
	if (isset($_SERVER)) 
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && validip($_SERVER['HTTP_X_FORWARDED_FOR'])) 
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif (isset($_SERVER['HTTP_CLIENT_IP']) && validip($_SERVER['HTTP_CLIENT_IP'])) 
		$ip = $_SERVER['HTTP_CLIENT_IP'];
		else
		$ip = $_SERVER['REMOTE_ADDR'];
	} 
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR') && validip(getenv('HTTP_X_FORWARDED_FOR'))) 
		$ip = getenv('HTTP_X_FORWARDED_FOR');
		elseif (getenv('HTTP_CLIENT_IP') && validip(getenv('HTTP_CLIENT_IP'))) 
		$ip = getenv('HTTP_CLIENT_IP');
		else
		$ip = getenv('REMOTE_ADDR');
	}
	return $ip;
}

//Returns the current PST time in MySQL compatible format.
function get_date_time($timestamp = 0)
{
	if ($timestamp)
	return date("Y-m-d H:i:s", $timestamp);
	else
	return date("Y-m-d H:i:s");
}

//Returns the numbers of rows in the MySQL table provided
function get_row_count($table, $suffix = "")
{
	if ($suffix)
	$suffix = " $suffix";
	$res = query("SELECT COUNT(*) FROM $table$suffix") or die(mysql_error());
	$arr = mysql_fetch_row($res) or die(mysql_error());
	return $arr[0];
}

//Returns the current user's class number
function get_user_class()
{
	global $CURUSER;
	return $CURUSER["class"];
}

//Returns the user class name that corresponds to a class number
function get_user_class_name($class)
{
	switch ($class)
	{
		case UC_USER: return "User";
		case UC_POWER_USER: return "Power User";
		case UC_ELITE_USER: return "Elite User";
		case UC_VIP: return "VIP";
		case UC_UPLOADER: return "Uploader";
		case UC_MODERATOR: return "Moderator";
		case UC_ADMINISTRATOR: return "Administrator";
		case UC_SYSOP: return "SysOp";
		default: return "Unknown Class";
	}
}

//Returns donated, warned or disabled, and parked icons for a user
function get_user_icons($arr, $big = false)
{
	if ($big)
	{
		$donorpic = "starbig.gif";
		$warnedpic = "warnedbig.gif";
		$disabledpic = "disabledbig.gif";
		$parkedpic = "parkedbig.gif";
		$style = "style='margin-left: 4pt'";
	}
	else
	{
		$donorpic = "star.gif";
		$warnedpic = "warned.gif";
		$disabledpic = "disabled.gif";
		$parkedpic = "parked.gif";
		$style = "style=\"margin-left: 2pt\"";
	}
	$pics = $arr["donor"] == "yes" ? "<img src=pic/$donorpic alt=\"Donor\" title=\"Donor\" border=0 $style>" : "";
	if ($arr["enabled"] == "yes")
	$pics .= $arr["warned"] == "yes" ? "<img src=pic/$warnedpic alt=\"Warned\" title=\"Warned\" border=0 $style>" : "";
	else
	$pics .= "<img src=pic/$disabledpic alt=\"Disabled\" title=\"Disabled\" border=0 $style>";
	$pics .= $arr["parked"] == "yes" ? "<img src=pic/$parkedpic alt=\"Parked\" title=\"Parked\" border=0 $style>" : "";
	return $pics;
}

//Prints an alert message and dies
function alert($heading, $text)
{
	stdhead($heading);
	print("<table class=main width=750 border=0 cellpadding=0 cellspacing=0><tr><td class=embedded>\n");
	print("<h2>$heading</h2>\n");
	print("<table width=100% border=1 cellspacing=0 cellpadding=10><tr><td class=text>\n");
	print($text . "</td></tr></table></td></tr></table>\n");
	stdfoot();
	die;
}

//Prints an error message and dies
function error($text = "An error occurred")
{
	alert("Error", $text);
}

//Prints an SQL error message and dies
function sqlerr($file = '', $line = '')
{
	print("<table border=0 bgcolor=blue align=left cellspacing=0 cellpadding=10 style='background: blue'>" .
	"<tr><td class=embedded><font color=white><h1>SQL Error</h1>\n" .
	"<b>" . mysql_error() . ($file != '' && $line != '' ? "<p>in $file, line $line</p>" : "") . "</b></font></td></tr></table>");
	die;
}

//Writes an event to the site log
function write_log($text)
{
	query("INSERT INTO sitelog (added, txt) VALUES (NOW(), " . sqlesc($text) . ")") or die(mysql_error());
}

//Writes an event to the admin log
function write_admin_log($text, $user)
{
	$user = (int)$user;
	query("INSERT INTO adminlog (userid, added, txt) VALUES ($user, NOW(), " . sqlesc($text) . ")") or die(mysql_error());
}

//Formats quote bbcodes into html within a body of text
function format_quotes($s)
{
	while ($old_s != $s)
	{
		$old_s = $s;

		//find first occurrence of [/quote]
		$close = strpos($s, "[/quote]");
		if ($close === false)
		return $s;

		//find last [quote] before first [/quote]
		//note that there is no check for correct syntax
		$open = strripos(substr($s,0,$close), "[quote");
		if ($open === false)
		return $s;

		$quote = substr($s,$open,$close - $open + 8);

		//[quote]Text[/quote]
		$quote = preg_replace(
		"/\[quote\]\s*((\s|.)+?)\s*\[\/quote\]\s*/i",
		"<p class=sub><b>Quote:</b></p><table class=main border=1 cellspacing=0 cellpadding=10><tr><td style='border: 1px black dotted'>\\1</td></tr></table><br />", $quote);

		//[quote=Author]Text[/quote]
		$quote = preg_replace(
		"/\[quote=(.+?)\]\s*((\s|.)+?)\s*\[\/quote\]\s*/i",
		"<p class=sub><b>\\1 wrote:</b></p><table class=main border=1 cellspacing=0 cellpadding=10><tr><td style='border: 1px black dotted'>\\2</td></tr></table><br />", $quote);

		$s = substr($s,0,$open) . $quote . substr($s,$close + 8);
	}
	return $s;
}

//Formats urls into html within a body of text
function format_urls($s)
{
//	return $s;
//	return preg_replace("/(\A|[^=\]'\"a-zA-Z0-9])((http|ftp|https|ftps|irc):\/\/[^()<>\s]+)/i","\\1<a href=\"http://hiderefer.com/?\\2\" target=\"_blank\">\\2</a>", $s);
	return preg_replace("/(\A|[^=\]'\"a-zA-Z0-9])((http|ftp|https|ftps|irc):\/\/[^()<>\s]+)/i","\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $s);
}

//make format_url() work with hiderefer
//add format_url() support for www.example.com
//fix image links in format_comment()

//Formats bbcodes, smilies, and linebreaks into html, and removes existing html, within a body of text
function format_comment($text, $strip_html = true)
{
	global $smilies, $privatesmilies;

	$s = $text;

	$s = str_replace(";)", ":wink:", $s);

	if ($strip_html)
		$s = htmlspecialchars($s);

	// [*]
	$s = preg_replace("/\[\*\]/", "<li>", $s);

	// [b]Bold[/b]
	$s = preg_replace("/\[b\]((\s|.)+?)\[\/b\]/", "<b>\\1</b>", $s);

	// [i]Italic[/i]
	$s = preg_replace("/\[i\]((\s|.)+?)\[\/i\]/", "<i>\\1</i>", $s);

	// [u]Underline[/u]
	$s = preg_replace("/\[u\]((\s|.)+?)\[\/u\]/", "<u>\\1</u>", $s);

	// [u]Underline[/u]
	$s = preg_replace("/\[u\]((\s|.)+?)\[\/u\]/i", "<u>\\1</u>", $s);

	// [img]http://www/image.gif[/img]
//	$s = preg_replace("/\[img\](http:\/\/[^\s'\"<>]+(\.(jpg|gif|png)))\[\/img\]/i", 
//		"<img border=\"0\" src=\"\\1\" onLoad='SetSize(this)'><br />Click <a href=\"http://hiderefer.com/?\\1\" target=\"_blank\">here</a> to view the original image.", $s);
	$s = preg_replace("/\[img\](http:\/\/[^\s'\"<>]+(\.(jpg|gif|png)))\[\/img\]/i", "<img border=0 src=\"\\1\" onLoad='SetSize(this)' />", $s);

	// [img=http://www/image.gif]
//	$s = preg_replace("/\[img=(http:\/\/[^\s'\"<>]+(\.(gif|jpg|png)))\]/i", 
//		"<img border=\"0\" src=\"\\1\" onLoad='SetSize(this)'><br />Click <a href=\"http://hiderefer.com/?\\1\" target=\"_blank\">here</a> to view the original image.", $s);
	$s = preg_replace("/\[img=(http:\/\/[^\s'\"<>]+(\.(gif|jpg|png)))\]/i", "<img border=0 src=\"\\1\" onLoad='SetSize(this)' />", $s);

	// [color=blue]Text[/color]
	$s = preg_replace(
		"/\[color=([a-zA-Z]+)\]((\s|.)+?)\[\/color\]/i",
		"<font color=\\1>\\2</font>", $s);

	// [color=#ffcc99]Text[/color]
	$s = preg_replace(
		"/\[color=(#[a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9][a-f0-9])\]((\s|.)+?)\[\/color\]/i",
		"<font color=\\1>\\2</font>", $s);

	// [url=http://www.example.com]Text[/url]
//	$s = preg_replace(
//		"/\[url=([^()<>\s]+?)\]((\s|.)+?)\[\/url\]/i",
//		"<a href=\"http://hiderefer.com/?\\1\" target=\"_blank\">\\2</a>", $s);
	$s = preg_replace(
		"/\[url=([^()<>\s]+?)\]((\s|.)+?)\[\/url\]/i",
		"<a href=\"\\1\" target=\"_blank\">\\2</a>", $s);

	// [url]http://www.example.com[/url]
//	$s = preg_replace(
//		"/\[url\]([^()<>\s]+?)\[\/url\]/i",
//		"<a href=\"http://hiderefer.com/?\\1\" target=\"_blank\">\\1</a>", $s);
	$s = preg_replace(
		"/\[url\]([^()<>\s]+?)\[\/url\]/i",
		"<a href=\"\\1\" target=\"_blank\">\\1</a>", $s);

	// [size=4]Text[/size]
	$s = preg_replace(
		"/\[size=([1-7])\]((\s|.)+?)\[\/size\]/i",
		"<font size=\\1>\\2</font>", $s);

	// [font=Arial]Text[/font]
	$s = preg_replace(
		"/\[font=([a-zA-Z ,]+)\]((\s|.)+?)\[\/font\]/i",
		"<font face=\"\\1\">\\2</font>", $s);

	// Quotes
	$s = format_quotes($s);

	// URLs
	$s = format_urls($s);

	// Linebreaks
	$s = nl2br($s);

	// [pre]Preformatted[/pre]
	$s = preg_replace("/\[pre\]((\s|.)+?)\[\/pre\]/i", "<tt><nobr>\\1</nobr></tt>", $s);

	// [nfo]NFO-preformatted[/nfo]
	$s = preg_replace("/\[nfo\]((\s|.)+?)\[\/nfo\]/i", "<tt><nobr><font face='MS Linedraw' size=2 style='font-size: 10pt; line-height: " .
		"10pt'>\\1</font></nobr></tt>", $s);

	// Maintain spacing
	$s = str_replace("  ", " &nbsp;", $s);

	reset($smilies);
	while (list($code, $url) = each($smilies))
		$s = str_replace($code, "<img border=0 src=\"/pic/smilies/$url\" alt=\"" . htmlspecialchars($code) . "\">", $s);

	reset($privatesmilies);
	while (list($code, $url) = each($privatesmilies))
		$s = str_replace($code, "<img border=0 src=\"/pic/smilies/$url\">", $s);

	return $s;
}

//Begins the outer frame on a page
function begin_main_frame()
{
	print("<table class=main width=750 border=0 cellspacing=0 cellpadding=0><tr><td class=embedded>\n\n");
}

//Ends the outer frame on a page
function end_main_frame()
{
	print("</td></tr></table>\n\n");
}

//Begins an inner frame on a page
function begin_frame($caption = "", $center = false, $padding = 10)
{
	$tdextra = "";
    
	if ($caption)
	print("<h2>$caption</h2>\n");

	if ($center)
	$tdextra .= " align=center";

	print("<table width=100% border=1 cellspacing=0 cellpadding=$padding><tr><td$tdextra>\n");
}

//Ends an inner frame on a page
function end_frame()
{
	print("</td></tr></table>\n\n");
}

//Begins a table on a page
function begin_table($fullwidth = false, $padding = 5)
{
	$width = "";
    
	if ($fullwidth)
	$width .= " width=100%";
	print("<table class=main$width border=1 cellspacing=0 cellpadding=$padding>\n");
}

//Ends a table on a page
function end_table()
{
	print("</td></tr></table>\n");
}

//Returns the font color for a ratio
function get_ratio_color($ratio)
{
	if ($ratio < 0.1) return "#ff0000";
	if ($ratio < 0.2) return "#ee0000";
	if ($ratio < 0.3) return "#dd0000";
	if ($ratio < 0.4) return "#cc0000";
	if ($ratio < 0.5) return "#bb0000";
	if ($ratio < 0.6) return "#aa0000";
	if ($ratio < 0.7) return "#990000";
	if ($ratio < 0.8) return "#880000";
	if ($ratio < 0.9) return "#770000";
	if ($ratio < 1) return "#660000";
	return "#000000";
}

//merge with above function
function get_slr_color($ratio)
{
	if ($ratio < 0.025) return "#ff0000";
	if ($ratio < 0.05) return "#ee0000";
	if ($ratio < 0.075) return "#dd0000";
	if ($ratio < 0.1) return "#cc0000";
	if ($ratio < 0.125) return "#bb0000";
	if ($ratio < 0.15) return "#aa0000";
	if ($ratio < 0.175) return "#990000";
	if ($ratio < 0.2) return "#880000";
	if ($ratio < 0.225) return "#770000";
	if ($ratio < 0.25) return "#660000";
	if ($ratio < 0.275) return "#550000";
	if ($ratio < 0.3) return "#440000";
	if ($ratio < 0.325) return "#330000";
	if ($ratio < 0.35) return "#220000";
	if ($ratio < 0.375) return "#110000";
	return "#000000";
}

//modify this
function get_elapsed_time($ts)
{
	$mins = floor((time() - $ts) / 60);
	$hours = floor($mins / 60);
	$mins -= $hours * 60;
	$days = floor($hours / 24);
	$hours -= $days * 24;
	$weeks = floor($days / 7);
	$days -= $weeks * 7;
	$t = "";
	if ($weeks > 0)
	return "$weeks week" . ($weeks > 1 ? "s" : "");
	if ($days > 0)
	return "$days day" . ($days > 1 ? "s" : "");
	if ($hours > 0)
	return "$hours hour" . ($hours > 1 ? "s" : "");
	if ($mins > 0)
	return "$mins min" . ($mins > 1 ? "s" : "");
	return "< 1 min";
}

//remove this
function deadtime() 
{
	global $announce_interval;
	return time() - floor($announce_interval * 1.3);
}

//remove this (strtotime)
function sql_timestamp_to_unix_timestamp($s)
{
	return mktime(substr($s, 11, 2), substr($s, 14, 2), substr($s, 17, 2), substr($s, 5, 2), substr($s, 8, 2), substr($s, 0, 4));
}

//remove this
function mkprettytime($s) 
{
	if ($s < 0)
		$s = 0;
	$t = array();
	foreach (array("60:sec","60:min","24:hour","365:day","0:year") as $x) 
	{
		$y = explode(":", $x);
		if ($y[0] > 1) 
		{
			$v = $s % $y[0];
			$s = floor($s / $y[0]);
		}
		else
			$v = $s;
		$t[$y[1]] = $v;
	}
	
	if ($t["year"])
		return $t["year"] . " year" . ($t["year"] != 1 ? "s" : "") . ", " . $t["day"] . " day" . ($t["day"] != 1 ? "s" : "") . ", " . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
	if ($t["day"])
		return $t["day"] . " day" . ($t["day"] != 1 ? "s" : "") . ", " . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
	if ($t["hour"])
		return sprintf("%d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
//      if ($t["min"])
	return sprintf("%d:%02d", $t["min"], $t["sec"]);
//      return $t["sec"] . " secs";
}

function cleanup()
{
	global $torrent_dir, $signup_timeout, $max_dead_torrent_time, $SITENAME, $SITEURL, $SITEEMAIL;

	set_time_limit(0);
	ignore_user_abort(1);

	//delete unpaired torrents, torrent files, and peers
	do 
	{
		$res = query("SELECT id FROM torrents");
		$ar = array();
		while ($row = mysql_fetch_array($res)) 
		{
			$id = $row[0];
			$ar[$id] = 1;
		}

		if (!count($ar))
			break;

		$dp = @opendir($torrent_dir);
		if (!$dp)
			break;

		$ar2 = array();
		while (($file = readdir($dp)) !== false) 
		{
			if (!preg_match('/^(\d+)\.torrent$/', $file, $m))
				continue;
			$id = $m[1];
			$ar2[$id] = 1;
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$ff = $torrent_dir . "/$file";
			unlink($ff);
		}
		closedir($dp);

		if (!count($ar2))
			break;

		$delids = array();
		foreach (array_keys($ar) as $k) 
		{
			if (isset($ar2[$k]) && $ar2[$k])
				continue;
			$delids[] = $k;
			unset($ar[$k]);
		}
		if (count($delids))
			query("DELETE FROM torrents WHERE id IN (" . join(",", $delids) . ")");

		$res = query("SELECT torrent FROM peers GROUP BY torrent");
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if (isset($ar[$id]) && $ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			query("DELETE FROM peers WHERE torrent IN (" . join(",", $delids) . ")");

		$res = query("SELECT torrent FROM files GROUP BY torrent");
		$delids = array();
		while ($row = mysql_fetch_array($res)) {
			$id = $row[0];
			if ($ar[$id])
				continue;
			$delids[] = $id;
		}
		if (count($delids))
			query("DELETE FROM files WHERE torrent IN (" . join(",", $delids) . ")");
	} 
	while (0);

	$deadtime = deadtime();
	query("DELETE FROM peers WHERE last_action < FROM_UNIXTIME($deadtime)");

	$deadtime -= $max_dead_torrent_time;
	query("UPDATE torrents SET visible='no' WHERE visible='yes' AND last_action < FROM_UNIXTIME($deadtime)");

	$deadtime = time() - $signup_timeout;
	query("DELETE FROM users WHERE status = 'pending' AND added < FROM_UNIXTIME($deadtime) AND last_login < FROM_UNIXTIME($deadtime) AND last_access < FROM_UNIXTIME($deadtime)");

	//update torrent seeder/leecher/comments count
	$torrents = array();
	$res = query("SELECT torrent, seeder, COUNT(*) AS c FROM peers GROUP BY torrent, seeder");
	while ($row = mysql_fetch_assoc($res)) 
	{
		if ($row["seeder"] == "yes")
			$key = "seeders";
		else
			$key = "leechers";
		$torrents[$row["torrent"]][$key] = $row["c"];
	}
	$res = query("SELECT torrent, COUNT(*) AS c FROM comments GROUP BY torrent");
	while ($row = mysql_fetch_assoc($res)) 
	{
		$torrents[$row["torrent"]]["comments"] = $row["c"];
	}
	$fields = explode(":", "comments:leechers:seeders");
	$res = query("SELECT id, seeders, leechers, comments FROM torrents");
	while ($row = mysql_fetch_assoc($res)) 
	{
		$id = $row["id"];
		$torr = $torrents[$id];
		foreach ($fields as $field) 
		{
			if (!isset($torr[$field]))
				$torr[$field] = 0;
		}
		$update = array();
		foreach ($fields as $field) 
		{
			if ($torr[$field] != $row[$field])
				$update[] = "$field = " . $torr[$field];
		}
		if (count($update))
			query("UPDATE torrents SET " . implode(",", $update) . " WHERE id = $id");
	}

	//lock topics where last post was made more than x days ago
	/*
	$secs = 365*86400;
	$res = query("SELECT topics.id FROM topics LEFT JOIN posts ON topics.lastpost = posts.id AND topics.sticky = 'no' WHERE " . time() . " - UNIX_TIMESTAMP(posts.added) > $secs") or sqlerr(__FILE__, __LINE__);
	while ($arr = mysql_fetch_assoc($res))
		query("UPDATE topics SET locked='yes' WHERE id=$arr[id]") or sqlerr(__FILE__, __LINE__);
	*/

	//remove expired warnings
	$res = query("SELECT id FROM users WHERE warned='yes' AND warneduntil < NOW() AND warneduntil <> '0000-00-00 00:00:00'") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0)
	{
		$dt = sqlesc(get_date_time());
		$msg = sqlesc("Your warning has been removed. Please abide by the rules from now on.\n");
		while ($arr = mysql_fetch_assoc($res))
		{
			query("UPDATE users SET warned = 'no', warneduntil = '0000-00-00 00:00:00' WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			query("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr[id], $dt, $msg, 0)") or sqlerr(__FILE__, __LINE__);
		}
	}

	// promote elite users
	$limit = 200*1024*1024*1024;
	$minratio = 1.05;
	$maxdt = sqlesc(get_date_time(time() - 86400*56));
	$res = query("SELECT id FROM users WHERE (class = '" . UC_USER . "' OR class = '" . UC_POWER_USER . "') AND uploaded >= $limit AND (uploaded / downloaded >= $minratio OR downloaded = 0) AND added < $maxdt") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0)
	{
		$dt = sqlesc(get_date_time());
		$msg = sqlesc("Congratulations, you have been auto-promoted to [b]Elite User[/b]. :)\nElite users can view torrent NFOs and other semi-restricted areas.\nYour account is also immune to deletion due to inactivity.\n");
		while ($arr = mysql_fetch_assoc($res))
		{
			query("UPDATE users SET class = 2 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			query("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr[id], $dt, $msg, 0)") or sqlerr(__FILE__, __LINE__);
		}
	}

	// promote power users
	$limit = 25*1024*1024*1024;
	$minratio = 1.05;
	$maxdt = sqlesc(get_date_time(time() - 86400*28));
	$res = query("SELECT id FROM users WHERE class = '" . UC_USER . "' AND uploaded >= $limit AND (uploaded / downloaded >= $minratio OR downloaded = 0) AND added < $maxdt") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0)
	{
		$dt = sqlesc(get_date_time());
		$msg = sqlesc("Congratulations, you have been auto-promoted to [b]Power User[/b]. :)\nPower users can view torrent NFOs and other semi-restricted areas.\nYour account is also immune to deletion due to inactivity.\n");
		while ($arr = mysql_fetch_assoc($res))
		{
			query("UPDATE users SET class = 1 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			query("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr[id], $dt, $msg, 0)") or sqlerr(__FILE__, __LINE__);
		}
	}

	// demote power users and elite users
	$minratio = 0.95;
	$res = query("SELECT id, class FROM users WHERE (class = '" . UC_POWER_USER . "' OR class = '" . UC_ELITE_USER . "') AND uploaded / downloaded < $minratio AND downloaded <> 0") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) > 0)
	{
		$dt = sqlesc(get_date_time());
		while ($arr = mysql_fetch_assoc($res))
		{
			$msg = sqlesc("You have been auto-demoted from [b]" . get_user_class_name($arr["class"]) . "[/b] to [b]User[/b] because your share ratio has dropped below $minratio.\n");
			query("UPDATE users SET class = 0 WHERE id = $arr[id]") or sqlerr(__FILE__, __LINE__);
			query("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $arr[id], $dt, $msg, 0)") or sqlerr(__FILE__, __LINE__);
		}
	}

	// update forum post/topic count
	$forums = array();
	$res = query("SELECT forumid, COUNT(DISTINCT topics.id) as topiccount, COUNT(posts.id) AS postcount FROM topics LEFT JOIN posts ON topics.id = posts.topicid GROUP BY forumid");
	while ($row = mysql_fetch_assoc($res)) 
	{
		$forums[$row["forumid"]]["topiccount"] = $row["topiccount"];
		$forums[$row["forumid"]]["postcount"] = $row["postcount"];
	}
	$fields = explode(":", "topiccount:postcount");
	$res = query("SELECT id, topiccount, postcount FROM forums");
	while ($row = mysql_fetch_assoc($res)) 
	{
		$id = $row["id"];
		$forum = $forums[$id];
		foreach ($fields as $field) 
		{
			if (!isset($forum[$field]))
				$forum[$field] = 0;
		}
		$update = array();
		foreach ($fields as $field) 
		{
			if ($forum[$field] != $row[$field])
				$update[] = "$field = " . $forum[$field];
		}
		if (count($update))
			query("UPDATE forums SET " . implode(",", $update) . " WHERE id = $id");
	}

	// delete old torrents
	$days = 28;
	$dt = sqlesc(get_date_time(time() - ($days * 86400)));
	$res = query("SELECT torrents.id AS id, torrents.name AS name FROM torrents LEFT JOIN categories ON category = categories.id WHERE section != 2 AND added < $dt AND visible = 'no'");
	while ($arr = mysql_fetch_assoc($res))
	{
		@unlink("$torrent_dir/$arr[id].torrent");
		query("DELETE FROM torrents WHERE id=$arr[id]");
		query("DELETE FROM snatched WHERE torrentid =$arr[id]");
		query("DELETE FROM peers WHERE torrent=$arr[id]");
		query("DELETE FROM comments WHERE torrent=$arr[id]");
		query("DELETE FROM files WHERE torrent=$arr[id]");
		write_log("Torrent $arr[id] ($arr[name]) was deleted by system (older than $days days and dead)");
	}

	// warn inactive users
	$torrents = number_format(get_row_count("torrents"));
	$registered = number_format(get_row_count("users"));
	$seeders = number_format(get_row_count("peers", "WHERE seeder='yes'"));
	$leechers = number_format(get_row_count("peers", "WHERE seeder='no'"));
	$secs = ((30 * 6) - 7) * 86400;
	$dt = sqlesc(get_date_time(time() - $secs));
	$secs2 = 10*86400;
	$dt2 = sqlesc(get_date_time(time() - $secs2));
	
	$res=query("SELECT id, username, email, added, last_access, uploaded, downloaded, last_warned FROM users WHERE last_access < $dt AND last_warned < $dt2 AND class < '" . UC_POWER_USER . "' AND status='confirmed' AND parked = 'no' AND enabled = 'yes'");

	if(mysql_num_rows($res))
	{
		while($arr = mysql_fetch_assoc($res))
		{
			$id = $arr["id"];
			$username = $arr["username"];
			$email = $arr["email"];
			$added = $arr["added"];
			$last_access = $arr["last_access"];

			$subject = "Your $SITENAME account will be deleted in 7 days!";
$message = "Hi!

Your account at $SITENAME ($SITEURL) has been marked as inactive, and will be deleted in seven days if not accessed before then. 
If you wish to remain a member at $SITENAME, please login.

If you aren't on campus right now but would like to save your account, you can login to $SITENAME through the UBC VPN. 
For more information please visit http://www.it.ubc.ca/security/VPN/setupdocs.html

We currently have $registered members and $torrents active torrents, with $seeders seeders and $leechers leechers.

Your username is: $username
Your account was created on: $added
Your account was last accessed on: $last_access

You can login at: $SITEURL/login.php
If you have forgotten your password, you can retrieve it at: $SITEURL/recover.php

Regards, 

The $SITENAME Team.";

			$headers = "From:$SITEEMAIL\r\nReply-To:$SITEEMAIL\r\nX-Mailer: PHP/" . phpversion();

			mail($email, $subject, $message, $headers);

			query("UPDATE users SET last_warned = NOW() WHERE id = $id") or sqlerr();

		}
	}

	// delete inactive users
	$secs = 30*6*86400;
	$dt = sqlesc(get_date_time(time() - $secs));
	$secs2 = 7*86400;
	$dt2 = sqlesc(get_date_time(time() - $secs2));
	query("DELETE FROM users WHERE parked='no' AND enabled='yes' AND status='confirmed' AND class < '" . UC_POWER_USER . "' AND last_access < $dt AND last_warned < $dt2");

	// disable duplicate accounts for previously disabled users
	$res = query("SELECT identhash FROM users WHERE identhash <> '' GROUP BY identhash HAVING COUNT(*) > 1 AND MIN(enabled) = 'no' AND MAX(enabled) = 'yes'");
	while($arr = mysql_fetch_assoc($res))
	{
		query("UPDATE users SET enabled = 'no' WHERE enabled = 'yes' AND identhash = '" . $arr["identhash"] . "'");
	}

	/***Find Latest Weather***/

	$fp = fopen("http://rss.theweathernetwork.com/weather/cabc0308",'r');
	$data = fread($fp, 1700);
	fclose($fp);

	$weather=0;
	if (preg_match ("/rain/i", $data) || preg_match ("/shower/i", $data) || preg_match ("/drizzle/i", $data))
	$weather=1;
	if (preg_match ("/snow/i", $data) || preg_match ("/flurries/i", $data))
	$weather=2;

	query("UPDATE misc SET value = '$weather' WHERE arg = 'weather'");


	$now = time();
	query("UPDATE misc SET value = '$now' WHERE arg = 'lastcleantime'");
}

function dbconn($autoclean = false)
{
	global $mysql_host, $mysql_user, $mysql_pass, $mysql_db;

	if (!@mysql_connect($mysql_host, $mysql_user, $mysql_pass))
	{
		switch (mysql_errno())
		{
			case 1040:
			case 2002:
				if ($_SERVER[REQUEST_METHOD] == "GET")
				die("<html><head><meta http-equiv=refresh content=\"5 $_SERVER[REQUEST_URI]\"></head><body><table border=0 width=100% height=100%><tr><td><h3 align=center>The server load is very high at the moment. Retrying, please wait...</h3></td></tr></table></body></html>");
				else
				die("Too many users. Please press the Refresh button in your browser to retry.");
			default:
				die("[" . mysql_errno() . "] dbconn: mysql_connect: " . mysql_error());
		}
	}

	mysql_select_db($mysql_db) or die('dbconn: mysql_select_db: ' + mysql_error());

	userlogin();

	if ($autoclean)
	register_shutdown_function("autoclean");
}

function userlogin() 
{
	unset($GLOBALS["CURUSER"]);
	$ip = getip();
	//$subnet = substr($ip, 0, strrpos($ip, '.'));

	if (empty($_COOKIE["uid"]) || empty($_COOKIE["pass"]))
	return;
	$id = (int)$_COOKIE["uid"];
	if (!$id || strlen($_COOKIE["pass"]) != 32)
	return;
	$res = query("SELECT * FROM users WHERE id = $id AND enabled = 'yes' AND status = 'confirmed'");
	$row = mysql_fetch_array($res);
	if (!$row)
	return;
	if ($_COOKIE["pass"] !== md5("a7bj2xjsk" . $row["passhash"] . "h34kjk13"))
	return;
	query("UPDATE users SET last_access = NOW(), ip = " . sqlesc($ip) . ", identhash = " . sqlesc($_COOKIE["ident"]) . " WHERE id = " . $row["id"]);
	$row['ip'] = $ip;
	$GLOBALS["CURUSER"] = $row;
}

function autoclean() 
{
	global $autoclean_interval;
	$now = time();

	$lastcleaned = mysql_result(query("SELECT value FROM misc WHERE arg = 'lastcleantime'"), 0);

	if ($lastcleaned + $autoclean_interval <= $now)
	cleanup();
}

//Returns a formatted file size with units
function bytesize($bytes)
{
	$bytes = max(0, $bytes);
	if ($bytes < 1000 * 1024)
		return number_format($bytes / 1024, 2) . " kB";
	elseif ($bytes < 1000 * 1048576)
		return number_format($bytes / 1048576, 2) . " MB";
	elseif ($bytes < 1000 * 1073741824)
		return number_format($bytes / 1073741824, 2) . " GB";
	else
		return number_format($bytes / 1099511627776, 2) . " TB";
}

//remove this
function mkglobal($vars) 
{
	if (!is_array($vars))
	$vars = explode(":", $vars);
	foreach ($vars as $v) 
	{
		if (isset($_GET[$v]))
		$GLOBALS[$v] = unesc($_GET[$v]);
		elseif (isset($_POST[$v]))
		$GLOBALS[$v] = unesc($_POST[$v]);
		else
		return 0;
	}
	return 1;
}

function tr($x,$y,$noesc=0) 
{
	if ($noesc)
	$a = $y;
	else 
	{
		$a = htmlspecialchars($y);
		$a = str_replace("\n", "<br />\n", $a);
	}
	print("<tr><td class=\"heading\" valign=\"top\" align=\"right\">$x</td><td valign=\"top\" align=left>$a</td></tr>\n");
}

//remove this
function unesc($x)
{
	if (get_magic_quotes_gpc())
	return stripslashes($x);
	return $x;
}

function sqlesc($x) 
{
	return "'".mysql_real_escape_string($x)."'";
}

//move to browse.php
function sqlwildcardesc($x) 
{
	return str_replace(array("%","_"), array("\\%","\\_"), mysql_real_escape_string($x));
}

function stdhead($title = "", $msgalert = true) 
{
	global $CURUSER, $SITENAME, $SITEURL, $funds;

	header("Content-Type: text/html; charset=iso-8859-1");
	//header("Pragma: No-cache");
	if (!$title)
	$title = $SITENAME . (isset($_GET['tbv']) ? " (" . TBVERSION . ")" : "");
	else
	$title = $SITENAME . (isset($_GET['tbv']) ? " (" . TBVERSION . ")" : "") . " :: " . htmlspecialchars($title);

	if ($CURUSER)
	{
		$ss_a = @mysql_fetch_array(@query("select uri from stylesheets where id = " . $CURUSER["stylesheet"]));
		if ($ss_a)
			$ss_uri = $ss_a["uri"];
		$logo_a = @mysql_fetch_array(@query("select uri from logos where id = " . $CURUSER["logo"]));
		if ($logo_a)
			$logo_uri = $logo_a["uri"];
	}
	
	if (!$ss_uri)
	{
		$r = query("SELECT uri FROM stylesheets WHERE id = 1") or die(mysql_error());
		$a = mysql_fetch_array($r) or die(mysql_error());
		$ss_uri = $a["uri"];
	}
	if (!$logo_uri)
	{
		$r = query("SELECT uri FROM logos WHERE id = 1") or die(mysql_error());
		$a = mysql_fetch_array($r) or die(mysql_error());
		$logo_uri = $a["uri"];
	}

//<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
?>
<html><head>
<title><?= $title ?></title>
<link rel="stylesheet" href="/<?=$ss_uri?>" type="text/css">
<? if ($CURUSER) { ?>
<link rel="alternate" type="application/rss+xml" title="Latest Torrents" href="<?=$SITEURL?>/rss.php">
<? } ?>

<script type="text/javascript">
function SetSize(obj) {
       if (obj.offsetWidth > 500) {
       obj.style.width = 500;
   };
};
</script>

<script type="text/javascript" src="<?=$SITEURL?>/include/showhide.js"></script>

</head>
<body>

<?
if ($CURUSER)
{
if ($CURUSER["view_weather"] == "yes")
{
$weatherid = mysql_result(query("SELECT value FROM misc WHERE arg = 'weather'"), 0);
if ($weatherid == 1)
print("<script type='text/javascript' src='$SITEURL/include/raindrops.js'></script>");
else if ($weatherid == 2)
print("<script type='text/javascript' src='$SITEURL/include/snowflakes.js'></script>");
}
}
?>

<table width="100%" cellspacing=0 cellpadding=0 style='background: transparent'>
<tr>
<td class=clear width="49%">

<?
/*
<table border=0 cellspacing=0 cellpadding=0 style='background: transparent'>
<tr>

<td class=clear>
<img src=/pic/star20.gif style='margin-right: 10px'>
</td>
<td class=clear>
<font color=white><b>Current funds: <?=$funds?></b></font>
</td>
</tr>
</table>
*/
?>

</td>
<td class=clear>
<div align=center>
<a href="/"><img src="/pic/<?=$logo_uri?>" alt="RezTorrent" border=0 align=middle></a>
</div>
</td>
<td class=clear width="49%" align=right>
</td>
</tr></table>
<?php

$w = "width=920";
//if ($_SERVER["REMOTE_ADDR"] == $_SERVER["SERVER_ADDR"]) $w = "width=920";

?>
<table class=mainouter <?=$w; ?> align=center border="1" cellspacing="0" cellpadding="5">

<!-- menu begins -->

<? $fn = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], "/") + 1); ?>
<tr><td class=outer align=center>
<? if ($CURUSER) { ?>
<table class=main width=600 cellspacing="0" cellpadding="5" border="0">
<? } else { ?>
<table class=main width=350 cellspacing="0" cellpadding="5" border="0">
<? } ?>
<tr>
<td align="center" class="navigation"><a href="/">Home</a></td>
<? if ($CURUSER) { ?>
<td align="center" class="navigation"><a href="/browse.php">Browse</a></td>
<td align="center" class="navigation"><a href="/browse2.php">Archive</a></td>
<td align="center" class="navigation"><a href="/upload.php">Upload</a></td>
<td align="center" class="navigation"><a href="/my.php">Profile</a></td>
<td align="center" class="navigation"><a href="/forums.php">Forums</a></td>
<td align="center" class="navigation"><a href="/users.php">Users</a></td>
<td align="center" class="navigation"><a href="/topten.php">Top 10</a></td>
<? } else { ?>
<td align="center" class="navigation"><a href="/login.php">Login</a> / <a href="/signup.php">Signup</a>
</td>
<? } ?>
<td align="center" class="navigation"><a href="/rules.php">Rules</a></td>
<td align="center" class="navigation"><a href="/faq.php">FAQ</a></td>
<td align="center" class="navigation"><a href="/staff.php">Staff</a></td>
</tr>
</table>

</td>
</tr>
<tr><td align=center class=outer style="padding-top: 15px; padding-bottom: 15px">


<?
if ($CURUSER)
{
$uped = bytesize($CURUSER['uploaded']);
$downed = bytesize($CURUSER['downloaded']);

if ($CURUSER["downloaded"] > 0)
{
$ratio = $CURUSER['uploaded'] / $CURUSER['downloaded'];
$ratio = number_format($ratio, 3);
$color = get_ratio_color($ratio);
if ($color)
$ratio = "<font color=\"$color\">$ratio</font>";
}
else
if ($CURUSER["uploaded"] > 0)
$ratio = "Inf.";
else
$ratio = "---";

//// check for messages //////////////////
$messages = get_row_count("messages", "WHERE receiver = $CURUSER[id] AND location IN ('in', 'both')");
$outmessages = get_row_count("messages", "WHERE sender = $CURUSER[id] AND location IN ('out', 'both')");

if ($msgalert)
	$unread = get_row_count("messages", "WHERE receiver = $CURUSER[id] AND location IN ('in', 'both') AND unread='yes'");
else
	$unread = 0;

if ($unread)
	$inboxpic = "<img height=14px style=border:none alt=Inbox title='Inbox (new messages)' src=$SITEURL/pic/inboxnew.gif>";
else
	$inboxpic = "<img height=14px style=border:none alt=Inbox title='Inbox (no new messages)' src=$SITEURL/pic/inbox.gif>";

//// check active torrents ///////////////////////
$activeseed = get_row_count("peers", "WHERE userid = $CURUSER[id] AND seeder='yes'");
$activeleech = get_row_count("peers", "WHERE userid = $CURUSER[id] AND seeder='no'");
?>


<table cellpadding="4" cellspacing="1" border="0" width=750 class="bottom"><tr><td class="tablea">
<table style="width:100%" cellspacing="0" cellpadding="0" border="0"><tr><td class="bottom" align="left">
<span class="smallfont">Welcome back, <b><a href="<?=$SITEURL?>/userdetails.php?id=<?=$CURUSER['id']?>"><?=$CURUSER['username']?></a></b><?print(get_user_icons($CURUSER))?>&nbsp;

<?
if (get_user_class() == UC_SYSOP)
print(" [<a href='$SITEURL/cpanel' target='_blank'>cPanel</a>] [<a href='http://webmail.reztorrent.org' target='_blank'>Webmail</a>]");
print(" [<a href='$SITEURL/logout.php'>logout</a>]<br />");
?>

<font color="#1900D1">Ratio:</font> <?=$ratio?>&nbsp;&nbsp;<font color="green">Uploaded:</font> <font color="black"><?=$uped?></font>&nbsp;&nbsp;<font color="darkred">Downloaded:</font> <font color="black"><?=$downed?></font>&nbsp;&nbsp;<font color="#1900D1">Active Torrents:&nbsp;</font></span> <img alt="Seeding" title="Seeding" src="<?=$SITEURL?>/pic/arrowup.gif">&nbsp;<font color="black"><span class="smallfont"><?if ($activeseed) {?><a href="<?=$SITEURL?>/userdetails.php?id=<?=$CURUSER['id']?>#seeding"><?}?><?=$activeseed?><?if ($activeseed) {?></a><?}?></span></font>&nbsp;&nbsp;<img alt="Leeching" title="Leeching" src="<?=$SITEURL?>/pic/arrowdown.gif">&nbsp;<font color="black"><span class="smallfont"><?if ($activeleech) {?><a href="<?=$SITEURL?>/userdetails.php?id=<?=$CURUSER['id']?>#leeching"><?}?><?=$activeleech?><?if ($activeleech) {?></a><?}?></span></font></td>
<td class="bottom" align="right"><span class="smallfont">The time is now: <?print(get_date_time());?><br />

<?
if ($messages)
{
print("<span class=smallfont><a href=\"$SITEURL/inbox.php\">$inboxpic</a> $messages ($unread New)</span>");
if ($outmessages)
print("<span class=smallfont>&nbsp;&nbsp;<a href=\"$SITEURL/inbox.php?out=1\"><img height=14px style=border:none alt=Sentbox title=Sentbox src=\"$SITEURL/pic/sentbox.gif\"></a> $outmessages</span>");
else
print("<span class=smallfont>&nbsp;&nbsp;<a href=\"$SITEURL/inbox.php?out=1\"><img height=14px style=border:none alt=Sentbox title=Sentbox src=\"$SITEURL/pic/sentbox.gif\"></a> 0</span>");
}
else
{
print("<span class=smallfont><a href=\"$SITEURL/inbox.php\"><img height=14px style=border:none alt=Inbox title=Inbox src=\"$SITEURL/pic/inbox.gif\"></a> 0</span>");
if ($outmessages)
print("<span class=smallfont>&nbsp;&nbsp;<a href=\"$SITEURL/inbox.php?out=1\"><img height=14px style=border:none alt=Sentbox title=Sentbox src=\"$SITEURL/pic/sentbox.gif\"></a> $outmessages</span>");
else
print("<span class=smallfont>&nbsp;&nbsp;<a href=\"$SITEURL/inbox.php?out=1\"><img height=14px style=border:none alt=Sentbox title=Sentbox src=\"$SITEURL/pic/sentbox.gif\"></a> 0</span>");
}
print("&nbsp;<a href=\"$SITEURL/friends.php\"><img style=border:none alt=Friends title=Friends src=\"$SITEURL/pic/friends.gif\"></a>");
print("&nbsp;<a href=\"$SITEURL/arcade.php\"><img style=border:none alt=Arcade title=Arcade src=\"$SITEURL/pic/arcade.gif\"></a>");
?>

</span></td>
</tr>
</table></td></tr></table>
<p />

<? 

if (!$CURUSER["downloaded"] && !$CURUSER["uploaded"] && $_SERVER['PHP_SELF'] != '/quickstart.php')
{
  print("<p><table border=0 cellspacing=0 cellpadding=10 bgcolor=red><tr><td style='padding: 10px; background: red'>\n");
  print("<b><a href=\"$SITEURL/quickstart.php\"><font color=white>Click here if you need help with downloading.</font></a></b>");
  print("</td></tr></table></p>\n");
}

if ($unread)
{
  print("<p><table border=0 cellspacing=0 cellpadding=10 bgcolor=red><tr><td style='padding: 10px; background: red'>\n");
  print("<b><a href=\"$SITEURL/inbox.php\"><font color=white>You have $unread new message" . ($unread > 1 ? "s" : "") . "!</font></a></b>");
  print("</td></tr></table></p>\n");
}

}

} // stdhead

function stdfoot() 
{
	global $starttime, $CURUSER;
	print("</td></tr></table>\n");
	if ($CURUSER)
	{
	print("<p align=center><font color=white><a class=altlink_white href=/arcade.php>Arcade</a> - <a class=altlink_white href=/friends.php>Friends</a>" . 
	" - <a class=altlink_white href=/log.php>Site Log</a> - <a class=altlink_white href=/getrss.php>Get RSS</a></font></p>\n");
	$endtime = explode(" ", microtime()); //Split Seconds and Microseconds
	$endtime = $endtime[1] + $endtime[0];  //Create a single value for end time
	$elapsed = round(($endtime - $starttime), 5);
	print("<p align=center><font color=white>Page executed with <b>" . $_SESSION["totalqueries"] . "</b> " . ($_SESSION["totalqueries"] == 1 ? "query" : "queries") . 
	" in $elapsed seconds.</font></p>\n");
	}
	
	echo '<div style="text-align:center; color:white; font-size:smaller; font-style:italic">In memory of eLucid, 1988 - 2010</div>';
	
	unset($_SESSION["totalqueries"]);
	print("</body></html>");
}

//Creates a random string
function mksecret($len = 20) 
{
	$ret = "";
	for ($i = 0; $i < $len; $i++)
	$ret .= chr(mt_rand(0, 255));
	return $ret;
}

//Creates a login cookie
function logincookie($id, $passhash, $updatedb = 1, $expires = 0x7fffffff)
{
	//$ip = getip();
	//$subnet = substr($ip, 0, strrpos($ip, '.'));

	setcookie("uid", $id, $expires, "/");
        setcookie("pass", md5("a7bj2xjsk" . $passhash . "h34kjk13"), $expires, "/");

	if (empty($_COOKIE["ident"]))
		setcookie("ident", md5(mt_rand() . get_date_time() . mt_rand()), $expires, "/");

	if ($updatedb)
		query("UPDATE users SET last_login = NOW() WHERE id = $id");
}

//Deletes a login cookie
function logoutcookie() 
{
	setcookie("uid", "", 0x7fffffff, "/");
	setcookie("pass", "", 0x7fffffff, "/");
}

//Only allows logged in users
function loggedinorreturn() 
{
	global $CURUSER, $SITEURL;
	if (!$CURUSER) 
	{
		header("Location: $SITEURL/login.php?returnto=" . urlencode($_SERVER["REQUEST_URI"]));
		exit();
	}
	else if ($CURUSER["parked"] == "yes" && $_SERVER['PHP_SELF'] != '/my.php' && $_SERVER['PHP_SELF'] != '/takeprofedit.php')
		error("Your account is parked. <a href=my.php>Click here</a> to unpark your account.");
}

//remove this or implement in cleanup
function deletetorrent($id) 
{
	global $torrent_dir;
	query("DELETE FROM torrents WHERE id = $id");
	query("DELETE FROM snatched WHERE torrentid = $id");
	foreach(explode(".","peers.files.comments.ratings") as $x)
	query("DELETE FROM $x WHERE torrent = $id");
	unlink("$torrent_dir/$id.torrent");
}

//Creates a page navigation menu
function pager($rpp, $count, $href, $opts = array()) 
{
	$pages = ceil($count / $rpp);

	if (!$opts["lastpagedefault"])
	$pagedefault = 0;
	else 
	{
		$pagedefault = floor(($count - 1) / $rpp);
		if ($pagedefault < 0)
		$pagedefault = 0;
	}

	if (isset($_GET["page"])) 
	{
		$page = 0 + $_GET["page"];
		if ($page < 0)
		$page = $pagedefault;
	}
	else
	$page = $pagedefault;

	$pager = "";

	$mp = $pages - 1;
	$as = "<b>&lt;&lt;&nbsp;Prev</b>";
	if ($page >= 1) 
	{
		$pager .= "<a href=\"{$href}page=" . ($page - 1) . "\">";
		$pager .= $as;
		$pager .= "</a>";
	}
	else
	$pager .= $as;
	$pager .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$as = "<b>Next&nbsp;&gt;&gt;</b>";
	if ($page < $mp && $mp >= 0) 
	{
		$pager .= "<a href=\"{$href}page=" . ($page + 1) . "\">";
		$pager .= $as;
		$pager .= "</a>";
	}
	else
	$pager .= $as;

	if ($count) 
	{
		$pagerarr = array();
		$dotted = 0;
		$dotspace = 3;
		$dotend = $pages - $dotspace;
		$curdotend = $page - $dotspace;
		$curdotstart = $page + $dotspace;
		for ($i = 0; $i < $pages; $i++) 
		{
			if (($i >= $dotspace && $i <= $curdotend) || ($i >= $curdotstart && $i < $dotend)) 
			{
				if (!$dotted)
				$pagerarr[] = "...";
				$dotted = 1;
				continue;
			}
			$dotted = 0;
			$start = $i * $rpp + 1;
			$end = $start + $rpp - 1;
			if ($end > $count)
			$end = $count;
			$text = "$start&nbsp;-&nbsp;$end";
			if ($i != $page)
			$pagerarr[] = "<a href=\"{$href}page=$i\"><b>$text</b></a>";
			else
			$pagerarr[] = "<b>$text</b>";
		}
		$pagerstr = join(" | ", $pagerarr);
		$pagertop = "<p align=\"center\">$pager<br />$pagerstr</p>\n";
		$pagerbottom = "<p align=\"center\">$pagerstr<br />$pager</p>\n";
	}
	else
	{
	$pagertop = "<p align=\"center\">$pager</p>\n";
	$pagerbottom = $pagertop;
	}

	$start = $page * $rpp;

	return array($pagertop, $pagerbottom, "LIMIT $start,$rpp");
}

function commenttable($rows)
{
	global $CURUSER;
	begin_main_frame();
	begin_frame();
	$count = 0;
	foreach ($rows as $row)
	{
		print("<p class=sub>#" . $row["id"] . " by ");
		if (isset($row["username"]))
		{
			$title = $row["title"];
			if ($title == "")
			$title = get_user_class_name($row["class"]);
			else
			$title = htmlspecialchars($title);
			print("<a name=comm". $row["id"] .
			" href=userdetails.php?id=" . $row["user"] . "><b>" .
			htmlspecialchars($row["username"]) . "</b></a>" . get_user_icons($row) . " ($title)\n");
		}
		else
		print("<a name=\"comm" . $row["id"] . "\"><i>(orphaned)</i></a>\n");

		print(" at " . $row["added"] . " PST" .
		($row["user"] == $CURUSER["id"] || get_user_class() >= UC_MODERATOR ? "- [<a href=comment.php?action=edit&amp;cid=$row[id]>Edit</a>]" : "") .
		(get_user_class() >= UC_MODERATOR ? "- [<a href=comment.php?action=delete&amp;cid=$row[id]>Delete</a>]" : "") .
		($row["editedby"] && get_user_class() >= UC_MODERATOR ? "- [<a href=comment.php?action=vieworiginal&amp;cid=$row[id]>View original</a>]" : "") . "</p>\n");
		$avatar = ($CURUSER["avatars"] == "yes" ? htmlspecialchars($row["avatar"]) : "");
		if (!$avatar)
		$avatar = "/pic/default_avatar.gif";
		$text = format_comment($row["text"]);
		if ($row["editedby"])
		{
			//find username from editedby user id
			$res2 = query("SELECT username FROM users WHERE id=$row[editedby]");
			if (mysql_num_rows($res2) == 1)
			{
				$arr2 = mysql_fetch_assoc($res2);
				$text .= "<p><font size=1 class=small>Last edited by <a href=userdetails.php?id=$row[editedby]><b>$arr2[username]</b></a> at $row[editedat] PST</font></p>\n";
			}
		}
		begin_table(true);
		print("<tr valign=top>\n");
		print("<td align=center width=150 style='padding: 0px'><img width=150 src=$avatar alt='Avatar'></td>\n");
		print("<td class=text>$text</td>\n");
		print("</tr>\n");
		end_table();
	}
	end_frame();
	end_main_frame();
}

function searchfield($s) 
{
	return preg_replace(array('/[^a-z0-9]/si', '/^\s*/s', '/\s*$/s', '/\s+/s'), array(" ", "", "", " "), $s);
}

function genrelist($section = null) 
{
	$ret = array();
	
	if (is_int($section))
		$res = query('SELECT id, name FROM categories WHERE section = '.$section.' ORDER BY id');
	else
		$res = query('SELECT id, name FROM categories ORDER BY id');
		
	while ($row = mysql_fetch_array($res))
		$ret[] = $row;
		
	return $ret;
}

//remove this?
function linkcolor($num) 
{
	if (!$num)
	return "red";
//      if ($num == 1)
//      return "yellow";
	return "green";
}

function ratingpic($num) 
{
	$r = round($num * 2) / 2;
	if ($r < 1 || $r > 5)
	return;
	return "<img src=\"/pic/$r.gif\" border=\"0\" alt=\"rating: $num / 5\" />";
}

function torrenttable($res, $variant = "index") 
{
	global $CURUSER;

	if (get_user_class() < UC_VIP)
	{
		$gigs = $CURUSER["uploaded"] / (1024*1024*1024);
		$ratio = (($CURUSER["downloaded"] > 0) ? ($CURUSER["uploaded"] / $CURUSER["downloaded"]) : 0);
		if ($ratio < 0.5 || $gigs < 5) $wait = 0;
		elseif ($ratio < 0.65 || $gigs < 6.5) $wait = 0;
		elseif ($ratio < 0.8 || $gigs < 8) $wait = 0;
		elseif ($ratio < 0.95 || $gigs < 9.5) $wait = 0;
		else $wait = 0;
	}
?>
<table border="1" cellspacing=0 cellpadding=5>
<tr>

<?

$count_get = 0;

foreach ($_GET as $get_name => $get_value) {

$get_name = mysql_escape_string(strip_tags(str_replace(array("\"","'"),array("",""),$get_name)));

$get_value = mysql_escape_string(strip_tags(str_replace(array("\"","'"),array("",""),$get_value)));

if ($get_name != "sort" && $get_name != "type") {
if ($count_get > 0) {
$oldlink = $oldlink . "&" . $get_name . "=" . $get_value;
} else {
$oldlink = $oldlink . $get_name . "=" . $get_value;
}
$count_get++;
}

}

if ($count_get > 0) {
$oldlink = $oldlink . "&";
}


if ($_GET['sort'] == "1") {
if ($_GET['type'] == "desc") {
$link1 = "asc";
} else {
$link1 = "desc";
}
}

if ($_GET['sort'] == "2") {
if ($_GET['type'] == "desc") {
$link2 = "asc";
} else {
$link2 = "desc";
}
}

if ($_GET['sort'] == "3") {
if ($_GET['type'] == "desc") {
$link3 = "asc";
} else {
$link3 = "desc";
}
}

if ($_GET['sort'] == "4") {
if ($_GET['type'] == "desc") {
$link4 = "asc";
} else {
$link4 = "desc";
}
}

if ($_GET['sort'] == "5") {
if ($_GET['type'] == "desc") {
$link5 = "asc";
} else {
$link5 = "desc";
}
}

if ($_GET['sort'] == "6") {
if ($_GET['type'] == "desc") {
$link6 = "asc";
} else {
$link6 = "desc";
}
}

if ($_GET['sort'] == "7") {
if ($_GET['type'] == "desc") {
$link7 = "asc";
} else {
$link7 = "desc";
}
}

if ($_GET['sort'] == "8") {
if ($_GET['type'] == "desc") {
$link8 = "asc";
} else {
$link8 = "desc";
}
}

if ($_GET['sort'] == "9") {
if ($_GET['type'] == "desc") {
$link9 = "asc";
} else {
$link9 = "desc";
}
}

if ($link1 == "") { $link1 = "asc"; } // for torrent name
if ($link2 == "") { $link2 = "desc"; }
if ($link3 == "") { $link3 = "desc"; }
if ($link4 == "") { $link4 = "desc"; }
if ($link5 == "") { $link5 = "desc"; }
if ($link6 == "") { $link6 = "desc"; }
if ($link7 == "") { $link7 = "desc"; }
if ($link8 == "") { $link8 = "desc"; }
if ($link9 == "") { $link9 = "desc"; }

?>

<td class="colhead" align="center">Type</td>
<td class="colhead" align="center">DL</td>
<td class="colhead" align="left"><a class=altlink_white href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=1&type=<? print $link1; ?>">Name</a></td>
<?
	if ($wait)
	{
		print("<td class=\"colhead\" align=\"center\">Wait</td>\n");
	}

	if ($variant == "mytorrents")
  {
  	print("<td class=\"colhead\" align=\"center\">Edit</td>\n");
    print("<td class=\"colhead\" align=\"center\">Visible</td>\n");
	}

?>
<td class="colhead" align="center"><a href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=2&type=<? print $link2; ?>"><img src=/pic/files.gif border=0></a></td>
<td class="colhead" align="center"><a href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=3&type=<? print $link3; ?>"><img src=/pic/comment.gif border=0></a></td>
<!--<td class="colhead" align="center">Rating</td>-->
<td class="colhead" align="center"><a class=altlink_white href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=4&type=<? print $link4; ?>">Added</a></td>
<!--<td class="colhead" align="center">TTL</td>-->
<td class="colhead" align="center"><a class=altlink_white href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=5&type=<? print $link5; ?>">Size</a></td>
<!--
<td class="colhead" align=right>Views</td>
<td class="colhead" align=right>Hits</td>
-->
<td class="colhead" align="center"><a class=altlink_white href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=6&type=<? print $link6; ?>">Snatched</a></td>
<td class="colhead" align="center"><a href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=7&type=<? print $link7; ?>"><img src=/pic/seeders.gif border=0></a></td>
<td class="colhead" align="center"><a href="<?=$_SERVER['PHP_SELF']?>?<? print $oldlink; ?>sort=8&type=<? print $link8; ?>"><img src=/pic/leechers.gif border=0></a></td>
<?

    if ($variant == "index")
        print("<td class=\"colhead\" align=center><a class=altlink_white href=\"" . $_SERVER['PHP_SELF'] . "?{$oldlink}sort=9&type={$link9}\">Uploader</a></td>\n");

    print("</tr>\n");

    while ($row = mysql_fetch_assoc($res)) {
        $id = $row["id"];
        print("<tr>\n");

        print("<td align=center style='padding: 0px'>");
        if (isset($row["cat_name"])) {
            print("<a href=\"" . $_SERVER['PHP_SELF'] . "?cat" . $row["category"] . "=1\">");
            if (isset($row["cat_pic"]) && $row["cat_pic"] != "")
                print("<img border=\"0\" src=\"/pic/" . $row["cat_pic"] . "\" alt=\"" . $row["cat_name"] . "\" />");
            else
                print($row["cat_name"]);
            print("</a>");
        }
        else
            print("-");
        print("</td>\n");

	print("<td align=center style='padding: 0px'>");
        print("<a href=\"download.php?id=$id\"><img src=pic/download.gif border=0 alt=Download></a>\n");
	print("</td>\n");

        $dispname = $row["name"];
	if (strlen($dispname) > 60)
	{
		print("<td align=left><a title=\"" . htmlspecialchars($dispname) . "\" href=\"details.php?");
		$dispname = substr($dispname,0,57);
		$dispname .= "...";
	}
	else
        	print("<td align=left><a href=\"details.php?");
        if ($variant == "mytorrents")
            print("returnto=" . urlencode($_SERVER["REQUEST_URI"]) . "&amp;");
        print("id=$id");
        if ($variant == "index")
            print("&amp;hit=1");
        print("\"><b>" . htmlspecialchars($dispname) . "</b></a>" . ($row['added'] >= $CURUSER['last_browse'] ? " <b>(<font color=red>NEW!</font>)</b>" : "") . "\n");

				if ($wait)
				{
				  $elapsed = floor((time() - strtotime($row["added"])) / 3600);
	        if ($elapsed < $wait)
	        {
	          $color = dechex(floor(127*($wait - $elapsed)/48 + 128)*65536);
	          print("<td align=center><nobr><a href=\"/faq.php#dl8\"><font color=\"$color\">" . number_format($wait - $elapsed) . " h</font></a></nobr></td>\n");
	        }
	        else
	          print("<td align=center><nobr>None</nobr></td>\n");
        }

/*
        if ($row["nfoav"] && get_user_class() >= UC_POWER_USER)
          print("<a href=viewnfo.php?id=$row[id]><img src=pic/viewnfo.gif border=0 alt='View NFO'></a>\n");
*/



            if ($variant == "mytorrents")
            print("<td align=\"center\"><a href=\"edit.php?returnto=" . urlencode($_SERVER["REQUEST_URI"]) . "&amp;id=" . $row["id"] . "\">edit</a>\n");
print("</td>\n");
        if ($variant == "mytorrents") {
            print("<td align=\"right\">");
            if ($row["visible"] == "no")
                print("<b>no</b>");
            else
                print("yes");
            print("</td>\n");
        }

        if ($row["type"] == "single")
            print("<td align=\"right\">" . $row["numfiles"] . "</td>\n");
        else {
            if ($variant == "index")
                print("<td align=\"right\"><b><a href=\"details.php?id=$id&amp;hit=1&amp;filelist=1\">" . $row["numfiles"] . "</a></b></td>\n");
            else
                print("<td align=\"right\"><b><a href=\"details.php?id=$id&amp;filelist=1#filelist\">" . $row["numfiles"] . "</a></b></td>\n");
        }

        if (!$row["comments"])
            print("<td align=\"right\">" . $row["comments"] . "</td>\n");
        else {
            if ($variant == "index")
                print("<td align=\"right\"><b><a href=\"details.php?id=$id&amp;hit=1&amp;tocomm=1\">" . $row["comments"] . "</a></b></td>\n");
            else
                print("<td align=\"right\"><b><a href=\"details.php?id=$id&amp;page=0#startcomments\">" . $row["comments"] . "</a></b></td>\n");
        }

/*
        print("<td align=\"center\">");
        if (!isset($row["rating"]))
            print("---");
        else {
            $rating = round($row["rating"] * 2) / 2;
            $rating = ratingpic($row["rating"]);
            if (!isset($rating))
                print("---");
            else
                print($rating);
        }
        print("</td>\n");
*/
        print("<td align=center><nobr>" . str_replace(" ", "<br />", $row["added"]) . "</nobr></td>\n");
/*		$ttl = (28*24) - floor((time() - sql_timestamp_to_unix_timestamp($row["added"])) / 3600);
		if ($ttl == 1) $ttl .= "<br />hour"; else $ttl .= "<br />hours";
        print("<td align=center>$ttl</td>\n");
*/
        print("<td align=center>" . str_replace(" ", "<br />", bytesize($row["size"])) . "</td>\n");
//        print("<td align=\"right\">" . $row["views"] . "</td>\n");
//        print("<td align=\"right\">" . $row["hits"] . "</td>\n");
        $_s = "";
        if ($row["times_completed"] != 1)
          $_s = "s";
	if (!$row["times_completed"])
	print("<td align=center>" . number_format($row["times_completed"]) . " time$_s</td>\n");
	else
        print("<td align=center><b><a href=details.php?id=$id&snatchlist=1#snatchlist>" . number_format($row["times_completed"]) . "</a></b> time$_s</td>\n");

        if ($row["seeders"]) {
            if ($variant == "index")
            {
               if ($row["leechers"]) $ratio = $row["seeders"] / $row["leechers"]; else $ratio = 1;
                print("<td align=right><b><a href=details.php?id=$id&amp;hit=1&amp;toseeders=1><font color=" .
                  get_slr_color($ratio) . ">" . $row["seeders"] . "</font></a></b></td>\n");
            }
            else
                print("<td align=\"right\"><b><a class=\"" . linkcolor($row["seeders"]) . "\" href=\"details.php?id=$id&amp;dllist=1#seeders\">" .
                  $row["seeders"] . "</a></b></td>\n");
        }
        else
            print("<td align=\"right\"><span class=\"" . linkcolor($row["seeders"]) . "\">" . $row["seeders"] . "</span></td>\n");

        if ($row["leechers"]) {
            if ($variant == "index")
                print("<td align=right><b><a href=details.php?id=$id&amp;hit=1&amp;todlers=1>" .
                   number_format($row["leechers"]) . ($peerlink ? "</a>" : "") .
                   "</b></td>\n");
            else
                print("<td align=\"right\"><b><a class=\"" . linkcolor($row["leechers"]) . "\" href=\"details.php?id=$id&amp;dllist=1#leechers\">" .
                  $row["leechers"] . "</a></b></td>\n");
        }
        else
            print("<td align=\"right\">0</td>\n");

        if ($variant == "index")
            print("<td align=center>" . (isset($row["username"]) ? ("<a href=userdetails.php?id=" . $row["owner"] . "><b>" . htmlspecialchars($row["username"]) . "</b></a>") : "<i>(unknown)</i>") . "</td>\n");

        print("</tr>\n");
    }

    print("</table>\n");

    return $rows;
}

function hash_pad($hash) 
{
	return str_pad($hash, 20);
}

function hash_where($name, $hash) 
{
	$shhash = preg_replace('/ *$/s', "", $hash);
	return "($name = " . sqlesc($hash) . " OR $name = " . sqlesc($shhash) . ")";
}

?>